package com.po.view.beans.util;




import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;

import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import oracle.adf.model.BindingContext;
import oracle.adf.model.DataControlFrame;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.model.binding.DCParameter;
import oracle.adf.share.ADFContext;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.event.PopupCanceledEvent;
import oracle.adf.view.rich.event.PopupFetchEvent;

import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;
import oracle.binding.ControlBinding;
import oracle.binding.OperationBinding;

import oracle.jbo.ApplicationModule;
import oracle.jbo.Key;
import oracle.jbo.Row;
import oracle.jbo.server.ViewRowSetImpl;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.model.CollectionModel;
import org.apache.myfaces.trinidad.model.RowKeySet;


public class ADFUtil {
  public ADFUtil() {
    super();
  }

  /**
   * Constant for signalling failed SRService checkout during eager test.
   */
  public static final String SRSERVICE_CHECKOUT_FAILED = "SRServiceFailed";

  /**
   * Get application module for an application module data control by name.
   * @param name application module data control name
   * @return ApplicationModule
   */
  public static ApplicationModule getApplicationModuleForDataControl(String name) {
    return (ApplicationModule)JSFUtil.resolveExpression("#{data." + name +
                                                        ".dataProvider}");
  }

  /**
   * A convenience method for getting the value of a bound attribute in the
   * current page context programatically.
   * @param attributeName of the bound value in the pageDef
   * @return value of the attribute
   */
  public static Object getBoundAttributeValue(String attributeName) {
    return findControlBinding(attributeName).getInputValue();
  }

  /**
   * A convenience method for setting the value of a bound attribute in the
   * context of the current page.
   * @param attributeName of the bound value in the pageDef
   * @param value to set
   */
  public static void setBoundAttributeValue(String attributeName,
                                            Object value) {
    findControlBinding(attributeName).setInputValue(value);
  }

  /**
   * Returns the evaluated value of a pageDef parameter.
   * @param pageDefName reference to the page definition file of the page with the parameter
   * @param parameterName name of the pagedef parameter
   * @return evaluated value of the parameter as a String
   */
  public static Object getPageDefParameterValue(String pageDefName,
                                                String parameterName) {
    BindingContainer bindings = findBindingContainer(pageDefName);
    DCParameter param =
      ((DCBindingContainer)bindings).findParameter(parameterName);
    return param.getValue();
  }

  /**
   * Convenience method to find a DCControlBinding as an AttributeBinding
   * to get able to then call getInputValue() or setInputValue() on it.
   * @param bindingContainer binding container
   * @param attributeName name of the attribute binding.
   * @return the control value binding with the name passed in.
   *
   */
  public static AttributeBinding findControlBinding(BindingContainer bindingContainer,
                                                    String attributeName) {
    if (attributeName != null) {
      if (bindingContainer != null) {
        ControlBinding ctrlBinding =
          bindingContainer.getControlBinding(attributeName);
        if (ctrlBinding instanceof AttributeBinding) {
          return (AttributeBinding)ctrlBinding;
        }
      }
    }
    return null;
  }

  /**
   * Convenience method to find a DCControlBinding as a JUCtrlValueBinding
   * to get able to then call getInputValue() or setInputValue() on it.
   * @param attributeName name of the attribute binding.
   * @return the control value binding with the name passed in.
   *
   */
  public static AttributeBinding findControlBinding(String attributeName) {
    return findControlBinding(getPageBindingContainer(), attributeName);
  }

  /**
   * Return the current page's binding container.
   * @return the current page's binding container
   */
  public static BindingContainer getPageBindingContainer() {
    return (BindingContainer)JSFUtil.resolveExpression("#{bindings}");
  }

  /**
   * Return the Binding Container as a DCBindingContainer.
   * @return current binding container as a DCBindingContainer
   */
  public static DCBindingContainer getDCBindingContainer() {
    return (DCBindingContainer)getPageBindingContainer();
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding.
   *
   * Uses the value of the 'valueAttrName' attribute as the key for
   * the SelectItem key.
   *
   * @param iteratorName ADF iterator binding name
   * @param valueAttrName name of the value attribute to use
   * @param displayAttrName name of the attribute from iterator rows to display
   * @return ADF Faces SelectItem for an iterator binding
   */
  public static List<SelectItem> selectItemsForIterator(String iteratorName,
                                                        String valueAttrName,
                                                        String displayAttrName) {
    return selectItemsForIterator(findIterator(iteratorName), valueAttrName,
                                  displayAttrName);
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding with description.
   *
   * Uses the value of the 'valueAttrName' attribute as the key for
   * the SelectItem key.
   *
   * @param iteratorName ADF iterator binding name
   * @param valueAttrName name of the value attribute to use
   * @param displayAttrName name of the attribute from iterator rows to display
   * @param descriptionAttrName name of the attribute to use for description
   * @return ADF Faces SelectItem for an iterator binding with description
   */
  public static List<SelectItem> selectItemsForIterator(String iteratorName,
                                                        String valueAttrName,
                                                        String displayAttrName,
                                                        String descriptionAttrName) {
    return selectItemsForIterator(findIterator(iteratorName), valueAttrName,
                                  displayAttrName, descriptionAttrName);
  }

  /**
   * Get List of attribute values for an iterator.
   * @param iteratorName ADF iterator binding name
   * @param valueAttrName value attribute to use
   * @return List of attribute values for an iterator
   */
  public static List attributeListForIterator(String iteratorName,
                                              String valueAttrName) {
    return attributeListForIterator(findIterator(iteratorName), valueAttrName);
  }

  /**
   * Get List of Key objects for rows in an iterator.
   * @param iteratorName iterabot binding name
   * @return List of Key objects for rows
   */
  public static List<Key> keyListForIterator(String iteratorName) {
    return keyListForIterator(findIterator(iteratorName));
  }

  /**
   * Get List of Key objects for rows in an iterator.
   * @param iter iterator binding
   * @return List of Key objects for rows
   */
  public static List<Key> keyListForIterator(DCIteratorBinding iter) {
    List attributeList = new ArrayList();
    for (Row r : iter.getAllRowsInRange()) {
      attributeList.add(r.getKey());
    }
    return attributeList;
  }

  /**
   * Get List of Key objects for rows in an iterator using key attribute.
   * @param iteratorName iterator binding name
   * @param keyAttrName name of key attribute to use
   * @return List of Key objects for rows
   */
  public static List<Key> keyAttrListForIterator(String iteratorName,
                                                 String keyAttrName) {
    return keyAttrListForIterator(findIterator(iteratorName), keyAttrName);
  }

  /**
   * Get List of Key objects for rows in an iterator using key attribute.
   *
   * @param iter iterator binding
   * @param keyAttrName name of key attribute to use
   * @return List of Key objects for rows
   */
  public static List<Key> keyAttrListForIterator(DCIteratorBinding iter,
                                                 String keyAttrName) {
    List attributeList = new ArrayList();
    for (Row r : iter.getAllRowsInRange()) {
      attributeList.add(new Key(new Object[] { r.getAttribute(keyAttrName) }));
    }
    return attributeList;
  }

  /**
   * Get a List of attribute values for an iterator.
   *
   * @param iter iterator binding
   * @param valueAttrName name of value attribute to use
   * @return List of attribute values
   */
  public static List attributeListForIterator(DCIteratorBinding iter,
                                              String valueAttrName) {
    List attributeList = new ArrayList();
    for (Row r : iter.getAllRowsInRange()) {
      attributeList.add(r.getAttribute(valueAttrName));
    }
    return attributeList;
  }

  /**
   * Find an iterator binding in the current binding container by name.
   *
   * @param name iterator binding name
   * @return iterator binding
   */
  public static DCIteratorBinding findIterator(String name) {
    DCIteratorBinding iter = getDCBindingContainer().findIteratorBinding(name);
    if (iter == null) {
      throw new RuntimeException("Iterator '" + name + "' not found");
    }
    return iter;
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding with description.
   *
   * Uses the value of the 'valueAttrName' attribute as the key for
   * the SelectItem key.
   *
   * @param iter ADF iterator binding
   * @param valueAttrName name of value attribute to use for key
   * @param displayAttrName name of the attribute from iterator rows to display
   * @param descriptionAttrName name of the attribute for description
   * @return ADF Faces SelectItem for an iterator binding with description
   */
  public static List<SelectItem> selectItemsForIterator(DCIteratorBinding iter,
                                                        String valueAttrName,
                                                        String displayAttrName,
                                                        String descriptionAttrName) {
    List<SelectItem> selectItems = new ArrayList<SelectItem>();
    for (Row r : iter.getAllRowsInRange()) {
      selectItems.add(new SelectItem(r.getAttribute(valueAttrName),
                                     (String)r.getAttribute(displayAttrName),
                                     (String)r.getAttribute(descriptionAttrName)));
    }
    return selectItems;
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding.
   *
   * Uses the value of the 'valueAttrName' attribute as the key for
   * the SelectItem key.
   *
   * @param iter ADF iterator binding
   * @param valueAttrName name of value attribute to use for key
   * @param displayAttrName name of the attribute from iterator rows to display
   * @return ADF Faces SelectItem for an iterator binding
   */
  public static List<SelectItem> selectItemsForIterator(DCIteratorBinding iter,
                                                        String valueAttrName,
                                                        String displayAttrName) {
    List<SelectItem> selectItems = new ArrayList<SelectItem>();
    for (Row r : iter.getAllRowsInRange()) {
      selectItems.add(new SelectItem(r.getAttribute(valueAttrName),
                                     (String)r.getAttribute(displayAttrName)));
    }
    return selectItems;
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding.
   *
   * Uses the rowKey of each row as the SelectItem key.
   *
   * @param iteratorName ADF iterator binding name
   * @param displayAttrName name of the attribute from iterator rows to display
   * @return ADF Faces SelectItem for an iterator binding
   */
  public static List<SelectItem> selectItemsByKeyForIterator(String iteratorName,
                                                             String displayAttrName) {
    return selectItemsByKeyForIterator(findIterator(iteratorName),
                                       displayAttrName);
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding with discription.
   *
   * Uses the rowKey of each row as the SelectItem key.
   *
   * @param iteratorName ADF iterator binding name
   * @param displayAttrName name of the attribute from iterator rows to display
   * @param descriptionAttrName name of the attribute for description
   * @return ADF Faces SelectItem for an iterator binding with discription
   */
  public static List<SelectItem> selectItemsByKeyForIterator(String iteratorName,
                                                             String displayAttrName,
                                                             String descriptionAttrName) {
    return selectItemsByKeyForIterator(findIterator(iteratorName),
                                       displayAttrName, descriptionAttrName);
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding with discription.
   *
   * Uses the rowKey of each row as the SelectItem key.
   *
   * @param iter ADF iterator binding
   * @param displayAttrName name of the attribute from iterator rows to display
   * @param descriptionAttrName name of the attribute for description
   * @return ADF Faces SelectItem for an iterator binding with discription
   */
  public static List<SelectItem> selectItemsByKeyForIterator(DCIteratorBinding iter,
                                                             String displayAttrName,
                                                             String descriptionAttrName) {
    List<SelectItem> selectItems = new ArrayList<SelectItem>();
    for (Row r : iter.getAllRowsInRange()) {
      selectItems.add(new SelectItem(r.getKey(),
                                     (String)r.getAttribute(displayAttrName),
                                     (String)r.getAttribute(descriptionAttrName)));
    }
    return selectItems;
  }

  /**
   * Get List of ADF Faces SelectItem for an iterator binding.
   *
   * Uses the rowKey of each row as the SelectItem key.
   *
   * @param iter ADF iterator binding
   * @param displayAttrName name of the attribute from iterator rows to display
   * @return List of ADF Faces SelectItem for an iterator binding
   */
  public static List<SelectItem> selectItemsByKeyForIterator(DCIteratorBinding iter,
                                                             String displayAttrName) {
    List<SelectItem> selectItems = new ArrayList<SelectItem>();
    for (Row r : iter.getAllRowsInRange()) {
      selectItems.add(new SelectItem(r.getKey(),
                                     (String)r.getAttribute(displayAttrName)));
    }
    return selectItems;
  }

  /**
   * Find the BindingContainer for a page definition by name.
   *
   * Typically used to refer eagerly to page definition parameters. It is
   * not best practice to reference or set bindings in binding containers
   * that are not the one for the current page.
   *
   * @param pageDefName name of the page defintion XML file to use
   * @return BindingContainer ref for the named definition
   */
  private static BindingContainer findBindingContainer(String pageDefName) {
    BindingContext bctx = getDCBindingContainer().getBindingContext();
    BindingContainer foundContainer = bctx.findBindingContainer(pageDefName);
    return foundContainer;
  }


  public void commitSelection(ValueChangeEvent valueChangeEvent) {
    UIComponent source = valueChangeEvent.getComponent();
    source.processUpdates(FacesContext.getCurrentInstance());

    DCBindingContainer bc = ADFUtil.getBindingContainer();

    //  OperationBinding operation=bc.getOperationBinding("Execute");
    // operation.execute();
    OperationBinding operation = bc.getOperationBinding("Commit");
    operation.execute();
  }

  public static void saveAndContinue() {
    Map sessionMap =
      FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    BindingContext context =
      (BindingContext)sessionMap.get(BindingContext.CONTEXT_ID);
    String currentFrameName = context.getCurrentDataControlFrame();
    DataControlFrame dcFrame = context.findDataControlFrame(currentFrameName);
    dcFrame.commit();
    dcFrame.beginTransaction(null);
  }

  /**
   * Programmatic evaluation of EL.
   *
   * @param el EL to evaluate
   * @return Result of the evaluation
   */
  public static Object evaluateEL(String el) {
    try {
      FacesContext facesContext = FacesContext.getCurrentInstance();
      ELContext elContext = facesContext.getELContext();
      ExpressionFactory expressionFactory =
        facesContext.getApplication().getExpressionFactory();
      ValueExpression exp =
        expressionFactory.createValueExpression(elContext, el, Object.class);
      return exp.getValue(elContext);
    } catch (Exception e) {
      throw new FacesException("Error " + e.getLocalizedMessage());
    }
  }

  /**
   * Programmatic invocation of a method that an EL evaluates to.
   * The method must not take any parameters.
   *
   * @param el EL of the method to invoke
   * @return Object that the method returns
   */

  public static Object invokeEL(String el) {
    return invokeEL(el, new Class[0], new Object[0]);
  }

  /**
   * Programmatic invocation of a method that an EL evaluates to.
   *
   * @param el EL of the method to invoke
   * @param paramTypes Array of Class defining the types of the
   * parameters
   * @param params Array of Object defining the values of the
   * parametrs
   * @return Object that the method returns
   */
  public static Object invokeEL(String el, Class[] paramTypes,
                                Object[] params) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
      facesContext.getApplication().getExpressionFactory();
    MethodExpression exp =
      expressionFactory.createMethodExpression(elContext, el, Object.class,
                                               paramTypes);
    return exp.invoke(elContext, params);
  }

  /**
   * Sets a value into an EL object. Provides similar
   * functionality to
   * the &lt;af:setActionListener&gt; tag, except the
   * <code>from</code> is
   * not an EL. You can get similar behavior by using the
   * following...<br>
   * <code>setEL(<b>to</b>, evaluateEL(<b>from</b>))</code>
   *
   * @param el EL object to assign a value
   * @param val Value to assign
   */
  public static void setEL(String el, Object val) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
      facesContext.getApplication().getExpressionFactory();
    ValueExpression exp =
      expressionFactory.createValueExpression(elContext, el, Object.class);
    exp.setValue(elContext, val);
  }

  /**
   * Retrieve a pageFlowScope variable value.
   * @param varName Name of the variable
   * @return The value of the variable
   */
  public static String getPageFlowVariable(String varName) {
    AdfFacesContext ctx = AdfFacesContext.getCurrentInstance();
    Map pageFlowScopes = ctx.getPageFlowScope();
    Object pageFlowObject = pageFlowScopes.get(varName);
    String val = null;
    /* checking if the page flow object contains null value
             and if yes returning null value */
    if (pageFlowObject != null) {
      val = pageFlowObject.toString();
    }
    return val;
  }

  public static void setPageFlowVariable(String varName, Object varValue) {
    AdfFacesContext ctx = AdfFacesContext.getCurrentInstance();
    ctx.getPageFlowScope().put(varName, varValue);
  }

  public static void removePageFlowScopeVariable(String varName) {
    ADFContext.getCurrent().getPageFlowScope().remove(varName);
  }


  public static Object getRequestScopeVariable(String varName) {
    ADFContext ctx = ADFContext.getCurrent();
    Map reqScopes = ctx.getRequestScope();
    Object reqObject = reqScopes.get(varName);
    Object val = null;
    /* checking if the page flow object contains null value
        and if yes returning null value */
    if (reqObject != null) {
      val = reqObject;
    }
    return val;
  }

  public static String getSessionScopeVariable(String varName) {
    ADFContext ctx = ADFContext.getCurrent();
    Map sessionScopes = ctx.getSessionScope();
    Object reqObject = sessionScopes.get(varName);
    String val = null;
    /* checking if the page flow object contains null value
        and if yes returning null value */
    if (reqObject != null) {
      val = reqObject.toString();
    }
    return val;
  }

  public static void setSessionScopeVariable(String varName, Object value) {

    ADFContext.getCurrent().getSessionScope().put(varName, value);
  }

  public static void removeSessionScopeVariable(String varName) {
    ADFContext.getCurrent().getSessionScope().remove(varName);
  }


  public static void setRequestScopeVariable(String varName, Object value) {
    ADFContext.getCurrent().getRequestScope().put(varName, value);
  }

  public static void removeRequestScopeVariable(String varName) {
    ADFContext.getCurrent().getRequestScope().remove(varName);
  }


  /**
   * Find a particular UI component on the page, such as an inputText object.
   *
   * @param source The component that triggered the event
   * @param id The identifier of the component to find
   * @return The component that was looked for
   */
  public static UIComponent findComponentRecurseUp(UIComponent source,
                                                   String id) {
    if (source == null)
      return null;

    UIComponent comp = source.findComponent(id);
    if (comp != null) {
      return comp;
    } else {
      // Go to the parent. Call this method recursively and find again.
      return findComponentRecurseUp(source.getParent(), id);
    }
  }

  public static DCBindingContainer getBindingContainer() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExpressionFactory exp =
      facesContext.getApplication().getExpressionFactory();

    return (DCBindingContainer)exp.createValueExpression(facesContext.getELContext(),
                                                         "#{bindings}",
                                                         DCBindingContainer.class).getValue(facesContext.getELContext());
  }

  public static void cancelAndContinue() {
    Map sessionMap =
      FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    BindingContext context =
      (BindingContext)sessionMap.get(BindingContext.CONTEXT_ID);
    String currentFrameName = context.getCurrentDataControlFrame();
    DataControlFrame dcFrame = context.findDataControlFrame(currentFrameName);
    dcFrame.rollback();
    dcFrame.beginTransaction(null);
  }

  /**
   * To execute a method from bindings.
   *
   * @param pMethodName methodName
   * @return output of method execution.
   */
  public static Object executeOperationBinding(String pMethodName) {
    BindingContainer bindings = getBindings();
    OperationBinding operationBinding =
      bindings.getOperationBinding(pMethodName);
    return operationBinding.execute();
  }

  public static BindingContainer getBindings() {
    FacesContext fc = FacesContext.getCurrentInstance();
    return (BindingContainer)fc.getApplication().evaluateExpressionGet(fc,
                                                                       "#{bindings}",
                                                                       BindingContainer.class);
  }


  /**
   * To refresh a region programmatically.
   *
   * @param pUIComponent
   */
  public static void refreshRegion(UIComponent pUIComponent) {
    RequestContext afContext = RequestContext.getCurrentInstance();
    afContext.addPartialTarget(pUIComponent);
  }

  /**
   * Returns PopupHints for aligning popup to the specified component.
   *
   * @param source
   * @param alignType
   * @return
   */
  public static RichPopup.PopupHints getPopupHints(UIComponent source,
                                                   RichPopup.PopupHints.AlignTypes alignType) {
    RichPopup.PopupHints hints = new RichPopup.PopupHints();
    hints.add(RichPopup.PopupHints.HintTypes.HINT_ALIGN_ID,
              source).add(RichPopup.PopupHints.HintTypes.HINT_ALIGN,
                          alignType);

    return hints;
  }


  /**
   * Returns a set of selected row keys for the provided table.
   *
   * @param table
   * @return
   */
  public static Set<Key> getTableSelectedRowKeys(RichTable table) {

    Set<Key> retVal = new HashSet<Key>();
    for (Object opaqueFacesRowKey : table.getSelectedRowKeys()) {
      table.setRowKey(opaqueFacesRowKey);
      Object o = table.getRowData();
      JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
      retVal.add(rowData.getRow().getKey());
    }
    return retVal;
  }

  /**
   * Sets the table selected row key to the first row.
   * The SelectedRowKeySet needs to be set explicitly for table using multiple selections.
   * makeCurrent method and the selectedRow property on CollectionModel class are designed for single selection table.
   *
   * @param table
   */
  public static void setFirstRowAsSelectedRowKey(RichTable table) {
    // set selected row keys to the first row
    CollectionModel model = (CollectionModel)table.getValue();
    RowKeySet rks = table.getSelectedRowKeys();
    if (rks != null) {
      rks.clear();
      model.setRowIndex(0);
      rks.add(model.getRowKey());
      table.setSelectedRowKeys(rks);
    }
  }

  public static void saveAndContinue(ActionEvent actionEvent) {
    DCBindingContainer bc = ADFUtil.getBindingContainer();

    OperationBinding operation = bc.getOperationBinding("Commit");
    operation.execute();
  }

  public static void cancelAndContinue(ActionEvent actionEvent) {
    DCBindingContainer bc = ADFUtil.getBindingContainer();

    OperationBinding opBind = bc.getOperationBinding("Rollback");
    opBind.execute();

    if (!opBind.getErrors().isEmpty()) {
      System.out.println("Errors during Rollback " + opBind.getErrors());
    }
  }

  public static Object resolveExpression(String el) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
      facesContext.getApplication().getExpressionFactory();
    ValueExpression valueExp =
      expressionFactory.createValueExpression(elContext, el, Object.class);
    return valueExp.getValue(elContext);
  }

  public static void setValueToEL(String el, Object val) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
      facesContext.getApplication().getExpressionFactory();
    ValueExpression exp =
      expressionFactory.createValueExpression(elContext, el, Object.class);
    exp.setValue(elContext, val);
  }

  public static boolean isAuthenticated() {
    return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
  }

  public static String getLoggedInUserName() {
    return ADFContext.getCurrent().getSecurityContext().getUserName();
  }

  public static void refreshPage() {
    try {
      FacesContext.getCurrentInstance().renderResponse();
      ExternalContext ctx =
        FacesContext.getCurrentInstance().getExternalContext();
      String url =
        ctx.getRequestContextPath() + ctx.getRequestServletPath() + ctx.getRequestPathInfo();
      FacesContext.getCurrentInstance().getExternalContext().redirect(url);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  public static Object getDefaultCareCenter(Object pasId) {
    return ADFUtil.evaluateEL("#{sessionScope.PatientSpecialistBean.careCenterId}");
  }

  public static String convertNumberToString(Object o) {
    if (o != null && o instanceof oracle.jbo.domain.Number) {
      return String.valueOf(((oracle.jbo.domain.Number)o).intValue());
    }
    return null;
  }

  public void popupCancelled(PopupCanceledEvent popupCanceledEvent) {
    // Add event code here...
    ADFContext.getCurrent().getPageFlowScope().put("forceActivate", "false");
  }

  public void popupFetchListener(PopupFetchEvent popupFetchEvent) {
    // Add event code here...
    ADFContext.getCurrent().getPageFlowScope().put("forceActivate", "true");
  }

  public static List<Map> getRowMapList(String childVOName,
                                        String[] attributes) {
    Row dept =
      ((oracle.adfinternal.view.faces.model.binding.FacesCtrlHierNodeBinding)ADFUtil.evaluateEL("#{row}")).getRow();
    ViewRowSetImpl vrsi = (ViewRowSetImpl)dept.getAttribute(childVOName);
    return viewRowSetToListOfMaps(vrsi, attributes);
  }

  public static List viewRowSetToListOfMaps(ViewRowSetImpl vrsi,
                                            String[] attributes) {
    List<Map> rowMapList = new ArrayList();
    while (vrsi.hasNext()) {
      Row row = vrsi.next();
      Map map = new HashMap();
      for (String att : attributes) {
        map.put(att, row.getAttribute(att));
      }
      rowMapList.add(map);
    }
    System.out.println(rowMapList);
    return rowMapList;
  }


  public static boolean fileExists(File file) {
    try {
      System.out.println("Checking file existence: " + file.getAbsolutePath());
      if (file != null && file.exists()) {
        System.out.println("File exists");
        return true;
      }

    } catch (Exception e) {
      // TODO: Add catch code
      e.printStackTrace();
    }
    System.out.println("File doesn't exist");
    return false;
  }

  public static void deleteFile(File file) {
    try {
      System.out.println("Deleting file: " + file.getAbsolutePath());
      if (file != null && file.exists())
        file.delete();
      System.out.println("Completed deleting file: " + file.getAbsolutePath());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


}
